package com.ruoyi.framework.security.handle;

import com.ruoyi.framework.config.properties.CasProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.authentication.ExceptionMappingAuthenticationFailureHandler;
import org.springframework.stereotype.Service;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

@Service
public class CasAuthenticationFailureHandler extends ExceptionMappingAuthenticationFailureHandler {

    @Autowired
    private CasProperties casProperties;

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {

        String error_code="fail";
        String error_message="CAS登录失败,";

        if (exception instanceof UsernameNotFoundException){
            error_message+=exception.getMessage();
        }else if (exception instanceof AuthenticationServiceException){
            error_message+=exception.getMessage();
        }else{
            error_message+="系统错误";
        }

        // 对参数值进行编码
        String encodedError = URLEncoder.encode(error_message, StandardCharsets.UTF_8.toString())
                .replaceAll("\\+", "%20");

        getRedirectStrategy().sendRedirect(request, response, casProperties.getAppServerUrl()+"/casError?error_code="+error_code+"&error_message="+encodedError);

    }
}
